<template>
  <div class="formula-container">
    <div
      v-for="(item, index) in formulaList"
      :key="index"
      class="formula-list">
      <div class="formula-list-item" style="margin-right:50px;">
        <span class="label">字段名称</span>
        <el-autocomplete
          v-model="item.name"
          :fetch-suggestions="querySearch"
          :maxlength="10"
          class="input"
          placeholder="请输入字段名称"
          @input="inputFormula"
          @select="handleSelect($event, item)"
        />
        <!-- <el-input v-model="item.name" class="input" placeholder="请输入字段名称" /> -->
      </div>
      <div class="formula-list-item">
        <span class="label">字段计算公式:</span>
        <div v-if="!item.formula" class="light-word" @click="openEditFormulaDialog(index)">请输入公式</div>
        <el-tooltip v-else placement="top">
          <div slot="content">{{ item.formula }}</div>
          <div class="ellipsis light-word" @click="openEditFormulaDialog(index, item)">{{ item.formula }}</div>
        </el-tooltip>
      </div>
      <div v-if="index === 0" class="add-btn" @click="addItem">
        <!-- <img :src="addIcon" alt=""> -->
        添加
      </div>
      <div v-else class="delete-btn" @click="deleteItem(index)">
        <i class="delete-icon el-icon-delete"/>
      </div>
      <editFormulaDialog
        :ref="`editFormulaDialog${index}`"
        :is-quote-template-field="isQuoteTemplateField"
        :field-list="fieldList"
        :formula-list="formulaList"
        :item="item" />
    </div>
    <div class="quote-container">
      <div v-if="isShowSaveWord" class="save-field">
        <div class="text">保存到字段表（公式字段）</div>
        <el-switch
          v-model="isSave"
          class="fb-switch"/>
      </div>
    </div>
  </div>
</template>
<script>
import addIcon from '@/assets/reportManage/add_icon.png';
// import { getFieldList } from '@/api/reportManage';
import { getSettingList } from '@/api/setting';
import { mapState } from 'vuex';
// import { numerical } from '@/utils/numFormat';
import tip from '@/assets/help_icon.png';
import draggable from 'vuedraggable';
import editFormulaDialog from './editFormulaDialog';
export default {
  name: 'FormulaSetting',
  components: { draggable, editFormulaDialog },
  props: {
    lookInput: { // 监听输入框
      type: Boolean,
      default: false
    },
    isShowSaveWord: { // 是否展示保存到报表
      type: Boolean,
      default: true
    },
    isQuoteTemplateField: { // 是否增加引用临时字段
      type: Boolean,
      default: false
    },
    fieldListOpt: { // 是否增加引用临时字段
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      tip,
      // cascaderValue: [],
      addIcon,
      value: '',
      fieldList: [],
      fieldListOptions: [],
      formulaList: [{
        options: [], // 字段配置列宾
        name: '',
        isFocus: false,
        formula: ''
      }],
      isSave: false,
      quoteField: '',
      quoteTemplateField: '',
      quoteValue: '',
      collectField: []
    };
  },
  computed: {
    ...mapState({
      'fieldListCache': state => state.options.reportFieldList
    })
  },
  watch: {
    fieldListOpt(val) {
      if (this.quoteTemplateField && this.quoteTemplateField.id) {
        const isDeleteTemp = val.some(i => i.id === this.quoteTemplateField.id);
        if (!isDeleteTemp) this.quoteTemplateField = '';
      }
    }
  },
  created() {
    // if (this.fieldListCache && this.fieldListCache.length > 0) {
    //   this.fieldList = this.fieldListCache;
    //   let list = [];
    //   this.fieldList.forEach(i => {
    //     list = list.concat(i.fieldInfo);
    //   });
    //   this.fieldListOptions = list;
    //   this.getCollectField(this.fieldList);
    // } else {
    this.getField();
    window.removeReadOnly();
    // }
  },
  methods: {
    setDefaut(formulaList) {
      if (formulaList.length > 0) {
        this.formulaList = formulaList;
      }
    },
    inputFormula(e) {
      if (this.lookInput) {
        this.$emit('inputFormula', this.formulaList);
      }
    },
    addItem() {
      const initData = {
        options: [], // 字段配置列宾
        name: '',
        isFocus: false,
        formula: ''
      };
      this.formulaList.push(initData);
    },
    deleteItem(index) {
      if (this.formulaList.length > 1) {
        this.formulaList.splice(index, 1);
      } else {
        this.formulaList = [{
          options: [], // 字段配置列宾
          name: '',
          isFocus: false
        }];
      }
      this.$emit('freshFormula');
    },
    getCollectField(fieldList) {
      let collectField = [];
      fieldList.forEach(i => {
        if (i.name === '公式字段') {
          collectField = i.fieldInfo;
        }
      });
      this.collectField = collectField;
    },
    handleFieldData(data) {
      if (data && data.length) {
        data.forEach(it => {
          it.fieldInfo = it.item;
          if (it.item && it.item.length) {
            this.handleFieldData(it.item);
          }
        });
      }
    },
    async getField() {
      try {
        const res = await getSettingList({ notShowNoAuthTip: true });
        if (res.data) {
          let result = [];
          res.data.map(it => {
            if (it.id === 5) {
              result = it.item.find(item => item.id === 11).item;
            }
          });
          this.handleFieldData(result);
          this.fieldList = result;
          let list = [];
          this.fieldList.forEach(i => {
            list = list.concat(i.fieldInfo);
          });
          this.fieldListOptions = list;
          this.getCollectField(this.fieldList);
        }
      } catch (error) {
        console.error(error);
      }
    },
    querySearch(queryString, cb) {
      var collectField = this.collectField;
      var results = queryString ? collectField.filter(i => i.name.indexOf(queryString) >= 0) : collectField;
      results.forEach(i => {
        i.value = i.name;
      });
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    handleSelect(queryString, item) {
      const formulaObj = queryString.formulaObj || [];
      formulaObj.forEach(i => {
        if (i.postName) i.isVariate = true;
      });
      item.options = formulaObj;
      if (item.options) {
        item.formula = item.options.reduce((res, item) => {
          return res + '' + item.name;
        }, '');
      }
    },
    openEditFormulaDialog(index, item) {
      const refName = `editFormulaDialog${index}`;
      item && (item.oldOptions = JSON.parse(JSON.stringify(item.options)));
      this.$refs[refName][0].openDialog();
    }
  }
};
</script>
<style lang="scss" scoped>
.formula-container {
  @include scrollBar($x: hidden, $y: auto);
  .formula-list {
    margin-bottom: 16px;
    display: flex;
    align-items: center;
  }
  .formula-list-item {
    display: flex;
    align-items: center;
    .label {
      font-size: 14px;
      color: #666666;
      text-align: right;
      margin-right: 13px;
    }
    & ::v-deep {
      .el-input__inner {
        width: 240px;
        height: 32px;
      }
    }
  }
  .formula-option {
    width:240px;
    height:32px;
    border-radius:4px;
    border:1px solid rgba(221,221,221,1);
    cursor: pointer;
    display: flex;
    overflow: hidden;
    align-items: center;
    &.active {
      border: 1px solid #406EFF;
    }
  }
  .add-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 30px;
    cursor: pointer;
    font-size: 14px;
    color: #406EFF;
    margin-left: 10px;
  }
  .delete-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 30px;
    margin-left: 6px;
    height: 30px;
    cursor: pointer;
    .delete-icon {
      font-size: 16px;
      color: #6C6C6C;
    }
  }
}
.quote-container {
  .quote-formula-list {
    margin-bottom:10px;
    display: flex;
    align-items: center;
    position: relative;
  }
  .quote-list {
    display: flex;
    align-items: center;
    margin-top: 8px;
    .quote-title {
      margin-right: 40px;
      font-size:14px;
      font-family:PingFangSC-Regular,PingFang SC;
      font-weight:400;
      color:rgba(102,102,102,1);
    }
    .quote-input {
      width: 240px;
      margin-right: 16px;
      & ::v-deep {
        .el-input__inner {
          width: 240px;
          height: 32px;
        }
      }
    }
    .quote-tag {
      width:24px;
      height:24px;
      background:rgba(239,243,251,1);
      border-radius:4px;
      color: #406EFF;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 8px;
      cursor: pointer;
      font-size: 12px;
    }
  }
  .save-field {
    display: flex;
    align-items: center;
    margin-top: 24px;
    .text {
      font-size:14px;
      color:#666666;
      line-height:14px;
      margin-right: 12px;
    }
  }
}

.formula-scroll-container {
  display: flex;
  align-items: center;
  width: 100%;
  height: 100%;
  & ::v-deep {
    .el-scrollbar__wrap {
      overflow-y: hidden;
      overflow-x: scroll;
      width: 100%;
      height: 150%;
    }
    .el-scrollbar__view {
      display: flex;
      height: 100%;
      align-items: center;
    }
    .el-scrollbar__bar.is-vertical {
      display: none;
    }
  }
}
.formula-option-tag {
  padding: 0 8px;
  height:24px;
  background:rgba(239,243,251,1);
  border-radius:4px;
  color: #406EFF;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  cursor: pointer;
  font-size: 12px;
  margin: 0 4px;
  white-space: nowrap;
}
.tooltip-formula-content {
  display: flex;
  flex-wrap: wrap;
}
 .tip-text {
  font-size: 12px;
  color: #666;
  padding: 5px;
}
.light-word{
  width: 240px;
  color: #406EFF;
  cursor: pointer;
}
</style>
<style lang="scss">
.tooltip-formula {
  padding: 0;
  max-width: 240px;
  border: 1px solid #ddd !important;
  .formula-option-tag {
    margin: 4px;
  }
  .popper__arrow {
    border-top-color: #ddd !important;
  }
}
</style>
